<template>
  <div class="login">
    
    <h3 class="title">{{title}}</h3>


    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">


      <div class="tabs d-flex justify-content-around">
        <span @click="clickloginType('password')" :class="{activate:loginType=='password'}">账号登录</span>
        <span @click="clickloginType('sms')" :class="{activate:loginType=='sms'}">手机号登录</span>
      </div>

      <div class="content">
        <!-- <el-form-item prop="tenantId" v-if="tenantEnabled">
          <el-select v-model="loginForm.tenantId" filterable placeholder="请选择/输入公司名称" style="width: 100%">
            <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
            <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
          </el-select>
        </el-form-item> -->

        <!-- 账号密码登录 -->
        <el-form-item prop="username" v-if="loginType=='password'">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>

        <el-form-item prop="password" v-if="loginType=='password'">
          <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        




        <!-- 手机验证码登录 -->
        <el-form-item prop="phonenumber" v-if="loginType=='sms'">
          <el-input v-model="loginForm.phonenumber" type="text" auto-complete="off" placeholder="手机号">
            <svg-icon slot="prefix" icon-class="phonenumber" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>

        <el-form-item prop="smsCode"  v-if="loginType=='sms'">
          <el-input v-model="loginForm.smsCode" type="text" auto-complete="off" placeholder="验证码">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            <el-button  type="text" slot="suffix" :disabled="getCodeBut" @click="getPhoneCode">
              <span v-if="getCodeBut">已发送 ({{countdownTime}})</span>
              <span v-else>获取验证码</span>
            </el-button>
          </el-input>
        </el-form-item>

        <el-form-item prop="code" v-if="captchaEnabled &&loginType=='password'">
          <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>



        <div v-if="loginType=='password'" class="tis d-flex justify-content-between">
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <router-link class="c-base pointer f14" to="/retrieve">忘记密码?</router-link>
        </div>


        <el-form-item style="width:100%;">
          <el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>


      </div>
    </el-form>
  
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 zjmm All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import logoImg from '@/assets/logo/logo.svg'
import { getCodeImg,getTenantList,getCodeSms } from '@/api/login'
import { encrypt, decrypt } from '@/utils/jsencrypt'


export default {
  name: 'Login',
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      title_en: process.env.VUE_APP_TITLE_EN,
      codeUrl: '',
      logo: logoImg,
      loginForm: {
        phonenumber: null,
        smsCode: null,     

        tenantId: '',
        username: '',
        password: '',
        rememberMe: false,
        code: null,
        uuid: '',
      },
      disabledLogin: true,
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入您的账号' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
        ],
        code: [
          { required: true, trigger: 'change', message: '请输入验证码' },
        ],

        phonenumber: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          { pattern: this.$pattern.telRegex,   message: '请输入正确的电话',   trigger: ['blur']},
        ],
        smsCode: [{ required: true, trigger: 'blur', message: '请输入验证码' }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      // 租户开关
      tenantEnabled: true,
      tenantList:[],

      loginType: 'password', //1账号密码 2 手机验证码
      countdownTime:60,
      getCodeBut: false,

    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },

  },
  created() {
    this.getCode()
    this.getLoginData()
    this.initTenantList();
  },
  methods: {

    clickloginType(type) {
      if (this.loginType == type) {
       return   
      }
      this.loginType = type
      this.loginForm.username = null 
      this.loginForm.copassworde = null 
      this.loginForm.code = null 

      this.loginForm.smsCode = null 
      this.loginForm.phonenumber = null 
      switch (type) {
        case 1:
          this.getCode()
          break
        case 2:

          break
        default:
          break
      }
      this.resetForm("loginForm")
      this.getLoginData()
    },

    getPhoneCode() {
      this.$refs.loginForm.validateField('phonenumber', valid => {
        if (!valid) {
          getCodeSms({
            phonenumber : this.loginForm.phonenumber
          }).then(() => {
            this.getCodeBut = true
            this.countdownTime = 60
            var timer = setInterval(() => {
              this.countdownTime--
              if (this.countdownTime == 0) {
                this.getCodeBut = false
                this.countdownTime = 60
                clearInterval(timer)
              }
            }, 1000)
          })
        } 
      });
    },

    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.loginForm.uuid = res.data.uuid;
        }
      })
    },
    validLoginEable(){
      this.$refs.loginForm.validate((valid) => {
        this.disabledLogin = !valid
      });
    },
    getLoginData(){
      const rememberMe = localStorage.getItem('rememberMe');
      const tenantId = localStorage.getItem("tenantId");
      const username = localStorage.getItem('username');
      const password = localStorage.getItem('password');
      if (rememberMe) {
        this.loginForm = {
          tenantId: tenantId === null ? String(this.loginForm.tenantId) : tenantId,
          username: username === null ? String(this.loginForm.username) : username,
          password: password === null ? String(this.loginForm.password) : decrypt(String(password)),
          rememberMe: rememberMe === null ? false : Boolean(rememberMe)
        };
      }


    },
    /**
     * 获取租户列表
     */
    async initTenantList(){
      const { data } = await getTenantList();
      this.tenantEnabled = data.tenantEnabled === undefined ? true : data.tenantEnabled;
      this.$store.dispatch('app/toggleTenantEnable',this.tenantEnabled)
      if (this.tenantEnabled) {
        this.tenantList = data.voList;
        if (this.tenantList != null && this.tenantList.length !== 0) {
          this.loginForm.tenantId = this.tenantList[0].tenantId;
        }
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            localStorage.setItem("tenantId", String(this.loginForm.tenantId));
            localStorage.setItem('username', String(this.loginForm.username));
            localStorage.setItem('password', encrypt(String(this.loginForm.password)));
            localStorage.setItem('rememberMe', String(this.loginForm.rememberMe));
          } else {
            // 否则移除
            localStorage.removeItem("tenantId");
            localStorage.removeItem('username');
            localStorage.removeItem('password');
            localStorage.removeItem('rememberMe');
          }

      

          let reqData = JSON.parse(JSON.stringify(this.loginForm))
          reqData.grantType = this.loginType
          delete reqData.tenantId

          this.$store
          .dispatch('Login', reqData)
          .then(() => {
            this.$router.push({ path: this.redirect || '/' }).catch(() => {})
          })
          .catch(() => {
            this.loading = false
            if (this.captchaEnabled&&this.loginType=='password') {
              this.getCode()
            }
          })





        }
      })
    },
  },
  mounted(){
    

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped >

.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login2.jpg');
  background-size: cover;
}
.title {
  font-size: 4rem;
  margin-bottom: 3rem;
  text-align: center;
  color: #4c73d6;
  font-weight: 600;
}



.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 40rem;



    .tabs {
      padding: 2rem 0;
      border-bottom: 1px solid #dcdfe6;
      span {
        font-size: 1.8rem;
        cursor: pointer;
        color: #666;
        &.activate {
          color: #333;
          font-weight: 500;
          position: relative;
          &:after {
            content: ' ';
            width: 3rem;
            height: 0.5rem;
            border-radius: 0.5rem;
            position: absolute;
            background: #117df9;
            bottom: -2rem;
            left: calc(50% - 1.5rem);
          }
        }
      }
    }

    .content {
      padding: 25px 25px 5px 25px;
    }

  ::v-deep .el-input {
    height: 38px;
    input {
      height: 38px;
      // border-color:#aaa;
      border: 0 none;
      background-color: #ededed;
      color:#000;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
    fill: #222;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}

#login_bg{
  width:100%;
  height:100%;
  position: absolute;
  left:0;
  right:0;
  top:0;
  bottom:0;
  z-index: 1;
}
</style>
